package org.androidpush.activity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.Window;

import org.androidpush.R;
import org.androidpush.client.Constants;
import org.androidpush.client.LogUtil;
import org.androidpush.client.ServiceManager;
import org.androidpush.fragment.FindFragment;
import org.androidpush.fragment.LinkFragment;
import org.androidpush.fragment.MeFragment;
import org.androidpush.fragment.MessFragment;
import org.androidpush.fragment.NotificationActivity;
import org.androidpush.greendao.UserFriend;
import org.androidpush.greendao.UserFriendDao;
import org.androidpush.ui.ChangeColorIconWithTextView;
import org.androidpush.utils.ConstantUtils;
import org.androidpush.utils.DBUtils;
import org.androidpush.utils.PinyinComparator;
import org.androidpush.utils.PinyinUtils;

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements
        OnPageChangeListener, OnClickListener {

    private static final String LOGTAG = LogUtil
            .makeLogTag(MainActivity.class);

    private ViewPager mViewPager;
    private List<Fragment> mTabs = new ArrayList<Fragment>();
    private FragmentPagerAdapter mAdapter;
    private ActionBar actionBar;
    private UserFriendDao userFriendDao;
    public int[] Imgs = {R.drawable.f1, R.drawable.f2, R.drawable.f3, R.drawable.f4, R.drawable.f5,
            R.drawable.f6, R.drawable.f7, R.drawable.f8, R.drawable.f9};

    private List<ChangeColorIconWithTextView> mTabIndicator = new ArrayList<ChangeColorIconWithTextView>();
    private  ServiceManager serviceManage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xml_main);

        SharedPreferences sp = MainActivity.this.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_APPEND);
        String status = sp.getString(ConstantUtils.STATUS, "");

        String userId = ConstantUtils.getUserId(this);
        String url = ConstantUtils.URL + "JxhtWeb/FriendController/" + userId + "/quesyFriend";
        Log.d(LOGTAG, url);
        if(ConstantUtils.isNetworkConnected(this)){
            new FriendAsyncTask().execute(url);
        }
        // Start the service
        serviceManage = new ServiceManager(MainActivity.this);
        serviceManage.setNotificationIcon(R.drawable.notification);
        serviceManage.startService();
        List tag = new ArrayList();
        tag.add(status);
        serviceManage.setTags(tag);
        actionBar = getActionBar();
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.skyblue));

        setOverflowShowingAlways();
        /*getActionBar().setDisplayShowHomeEnabled(false);*/
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        userFriendDao = DBUtils.getUserFriendDao(MainActivity.this);
        initDatas();
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOnPageChangeListener(this);

    }

    private void initDatas() {

        MessFragment messFragment = new MessFragment();
        LinkFragment linkFragment = new LinkFragment();
        FindFragment findFragment = new FindFragment();
        MeFragment meFragment = new MeFragment();
        mTabs.add(messFragment);
        mTabs.add(linkFragment);
        mTabs.add(findFragment);
        mTabs.add(meFragment);

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mTabs.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mTabs.get(arg0);
            }
        };

        initTabIndicator();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    private void initTabIndicator() {
        ChangeColorIconWithTextView mess = (ChangeColorIconWithTextView) findViewById(R.id.id_bootom_mess);
        ChangeColorIconWithTextView link = (ChangeColorIconWithTextView) findViewById(R.id.id_bootom_link);
        ChangeColorIconWithTextView find = (ChangeColorIconWithTextView) findViewById(R.id.id_bootom_find);
        ChangeColorIconWithTextView me = (ChangeColorIconWithTextView) findViewById(R.id.id_bootom_me);

        mTabIndicator.add(mess);
        mTabIndicator.add(link);
        mTabIndicator.add(find);
        mTabIndicator.add(me);

        mess.setOnClickListener(this);
        link.setOnClickListener(this);
        find.setOnClickListener(this);
        me.setOnClickListener(this);

        mess.setIconAlpha(1.0f);
    }

    @Override
    public void onPageSelected(int arg0) {
    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
        if (positionOffset > 0) {
            ChangeColorIconWithTextView left = mTabIndicator.get(position);
            ChangeColorIconWithTextView right = mTabIndicator.get(position + 1);
            left.setIconAlpha(1 - positionOffset);
            right.setIconAlpha(positionOffset);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {

        resetOtherTabs();

        switch (v.getId()) {
            case R.id.id_bootom_mess:
                mTabIndicator.get(0).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(0, false);
                break;
            case R.id.id_bootom_link:
                mTabIndicator.get(1).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(1, false);
                break;
            case R.id.id_bootom_find:
                mTabIndicator.get(2).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(2, false);
                break;
            case R.id.id_bootom_me:
                mTabIndicator.get(3).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(3, false);
                break;
        }

    }

    private void resetOtherTabs() {
        for (int i = 0; i < mTabIndicator.size(); i++) {
            mTabIndicator.get(i).setIconAlpha(0);
        }
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    private void setOverflowShowingAlways() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        switch (item.getItemId()) {
            case R.id.action_add_friend: {
                break;
            }
            case R.id.action_feed: {
                break;
            }
            case R.id.action_notification: {
                intent.setClass(MainActivity.this, NotificationActivity.class);
                startActivity(intent);
                this.overridePendingTransition(R.anim.push_left_in,
                        R.anim.push_left_out);
                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    class FriendAsyncTask extends
            AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return ConstantUtils.getDateFrom(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (ConstantUtils.NET_ERROR.equals(result)) {
                return;
            }else {
                Log.d(LOGTAG,"ERROR:"+result);
                List<UserFriend> friendDatas = getFriendData(result);
                Collections.sort(friendDatas, new PinyinComparator());
                for (UserFriend friend : friendDatas) {
                    userFriendDao.insertOrReplace(friend);
                }
            }
        }
    }

    private List<UserFriend> getFriendData(String result) {
        List<UserFriend> listArray, newListArray = null;
        if(result!=null){
            listArray = ConstantUtils.parseJsonArrayWithGson(result, UserFriend.class);
            int i = 0;
            newListArray = new ArrayList<>();
            for (UserFriend userFriend : listArray) {
                String pinyin = PinyinUtils.getPingYin(userFriend.getFriendName());
                ;
                String Fpinyin = pinyin.substring(0, 1).toUpperCase();
                userFriend.setPinYinName(pinyin);
                if (i < 9) {
                    userFriend.setFriendImg(Imgs[i]);
                    i++;
                } else {
                    i = 0;
                }
                if (Fpinyin.matches("[A-Z]")) {
                    userFriend.setFirstPinYin(Fpinyin);
                } else {
                    userFriend.setFirstPinYin("#");
                }
                newListArray.add(userFriend);
            }
        }
        return newListArray;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DBUtils.closeDB();
    }
}
